package com.ruubypay.biz.mvc.workflow.service.impl;

import com.ruubypay.biz.mvc.workflow.model.request.HistroyProcessVo;
import com.ruubypay.biz.mvc.workflow.model.response.AuditProcessResponse;
import com.ruubypay.biz.activiti.CommonProcessService;
import com.ruubypay.biz.mvc.workflow.service.HistoryProcessService;
import com.ruubypay.web.common.page.DataGrid;
import com.ruubypay.web.common.utils.StringUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 历史的流程实例Service层
 * @author chenhaiyang
 */
@Service(value = "historyProcessService")
public class HistoryRrocessServiceImpl extends CommonProcessService implements HistoryProcessService{

    @Resource
    private ProcessEngine processEngine;

    @Override
    public DataGrid listDataHistoryProcesses(Map<String, Object> paramMap, Integer pageNumber, Integer pageSize) {

        HistoricProcessInstanceQuery historicProcessInstanceQuery =
                processEngine.getHistoryService().createHistoricProcessInstanceQuery().finished();

        String businessKey = String.valueOf(paramMap.get("businessKey"));
        if (StringUtils.isNotBlank(businessKey)) {
            historicProcessInstanceQuery.processInstanceBusinessKey(businessKey);
        }
        String processDefinitionName = String.valueOf(paramMap.get("processDefinitionName"));
        if(StringUtils.isNotBlank(processDefinitionName)){
            historicProcessInstanceQuery.processDefinitionName(processDefinitionName);
        }

        List<HistoricProcessInstance> historyProcessInstances =
                historicProcessInstanceQuery.orderByProcessInstanceEndTime()
                .desc()
                .listPage((pageNumber-1)*pageSize,pageSize);

        return new DataGrid(historicProcessInstanceQuery.count(), historyProcessInstances);
    }

    /**
     * 根据历史流程实例Id删除历史流程
     * @param histroyProcessVo 历史流程实例Id
     */
    @Override
    public void deleteHistoryProcess(HistroyProcessVo histroyProcessVo) {
        processEngine.getHistoryService().deleteHistoricProcessInstance(histroyProcessVo.getProcessInstanceId());
    }

    /**
     * 获取历史流程实例的审批进度与情况
     * @param processInstanceId 流程实例id
     * @return 返回历史意见等审批流程
     */
    @Override
    public List<AuditProcessResponse> histoicFlowList(String processInstanceId) {
        return getHistoicFlowList(processEngine,processInstanceId);
    }

    /**
     * 根据流程实例id获取当前的流程图片
     * @param processInstanceId processInstanceId 流程实例id
     * @return 返回图片base64的字符串
     * @throws IOException IO异常
     */
    @Override
    public String getNowTaskPng(String processInstanceId) throws IOException {
        return getNowTaskPngByProcessInstanceId(processEngine,processInstanceId);
    }
}
